Java 26-Day Course - Day 6: Arrays

Day 6: Arrays

An array is a data structure that stores data of the same type in contiguous memory. It has a fixed size and can be accessed quickly via index. Indexing starts from 0.

Array Declaration and Initialization

Let’s explore several ways to create arrays.

public class ArrayBasic {
    public static void main(String[] args) {
        // Method 1: Specify size only (initialized with default values)
        int[] numbers = new int[5]; // [0, 0, 0, 0, 0]
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;

        // Method 2: Declare and initialize at the same time
        int[] scores = {95, 80, 70, 100, 88};

        // Method 3: Initialize with the new keyword
        String[] fruits = new String[]{"apple", "banana", "grape"};

        // Array length
        System.out.println("Array length: " + scores.length); // 5

        // Access by index
        System.out.println("First score: " + scores[0]); // 95
        System.out.println("Last score: " + scores[scores.length - 1]); // 88

        // Print array elements
        for (int i = 0; i < fruits.length; i++) {
            System.out.println("Fruit " + (i + 1) + ": " + fruits[i]);
        }
    }
}

Enhanced for Loop (for-each)

A concise way to iterate over all elements of an array.

import java.util.Arrays;

public class EnhancedForLoop {
    public static void main(String[] args) {
        int[] numbers = {15, 23, 8, 42, 37, 11, 29};

        // Print all using enhanced for loop
        for (int num : numbers) {
            System.out.print(num + " ");
        }
        System.out.println();

        // Calculate sum and average
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        double average = (double) sum / numbers.length;
        System.out.println("Sum: " + sum);
        System.out.println("Average: " + average);

        // Find maximum and minimum values
        int max = numbers[0];
        int min = numbers[0];
        for (int num : numbers) {
            if (num > max) max = num;
            if (num < min) min = num;
        }
        System.out.println("Max: " + max);
        System.out.println("Min: " + min);

        // Arrays utility class
        Arrays.sort(numbers); // Sort
        System.out.println("Sorted: " + Arrays.toString(numbers));
    }
}

Multi-dimensional Arrays

Let’s work with 2D arrays consisting of rows and columns.

public class MultiDimensionalArray {
    public static void main(String[] args) {
        // 2D array declaration
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Print 2D array
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.printf("%3d", matrix[i][j]);
            }
            System.out.println();
        }

        // Traverse 2D array with enhanced for loop
        int total = 0;
        for (int[] row : matrix) {
            for (int val : row) {
                total += val;
            }
        }
        System.out.println("Total sum: " + total);

        // Jagged array (variable-length rows)
        int[][] jagged = new int[3][];
        jagged[0] = new int[]{1, 2};
        jagged[1] = new int[]{3, 4, 5};
        jagged[2] = new int[]{6};

        for (int[] row : jagged) {
            System.out.println(java.util.Arrays.toString(row));
        }
    }
}

Array Copy and Comparison

Let’s learn the important considerations when copying arrays.

import java.util.Arrays;

public class ArrayCopy {
    public static void main(String[] args) {
        int[] original = {1, 2, 3, 4, 5};

        // Shallow copy: only the reference is copied (points to the same array)
        int[] shallow = original;
        shallow[0] = 999;
        System.out.println("Original[0]: " + original[0]); // 999 (modified!)

        // Deep copy methods
        int[] copy1 = Arrays.copyOf(original, original.length);
        int[] copy2 = original.clone();
        int[] copy3 = new int[original.length];
        System.arraycopy(original, 0, copy3, 0, original.length);

        copy1[0] = 111;
        System.out.println("Original[0]: " + original[0]); // 999 (unaffected)
        System.out.println("Copy[0]: " + copy1[0]);         // 111

        // Array comparison
        int[] a = {1, 2, 3};
        int[] b = {1, 2, 3};
        System.out.println(a == b);              // false (reference comparison)
        System.out.println(Arrays.equals(a, b)); // true (content comparison)
    }
}

Today’s Exercises

  1. Score Statistics: Store 10 students’ scores in an array and print the highest score, lowest score, average, and the number of students above average.

  2. Array Reversal: Reverse the integer array {1, 2, 3, 4, 5, 6, 7} in-place without creating a new array. (Use swap)

  3. Matrix Addition: Declare two 3x3 2D arrays and print the result matrix obtained by adding corresponding elements of both matrices.

Was this article helpful?